package com.doform.android.xianggucheng.activity.library;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.doform.android.xianggucheng.BaseTimePickerActivity;
import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.LibraryBean2;
import com.doform.android.xianggucheng.bean.request_bean.ReqDeleteInLibraryBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListInLibraryBean;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * 作者 Y_MS
 * Created by ${APEN} on 2017-07-17.
 * GitHub：https://github.com/cxydxpx
 */

public class ListInLibraryActivity extends BaseTimePickerActivity implements OnRefreshListener, OnLoadmoreListener {

    @BindView(R.id.tv_new_order)
    TextView mNewOrder;

    @BindView(R.id.tv_in_library)
    TextView mInLibrary;

    @BindView(R.id.tv_return_money)
    TextView mMonery;

    @BindView(R.id.tv_query_start)
    TextView mQueryStart;

    @BindView(R.id.tv_query_stop)
    TextView mQueryStop;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.ll)
    LinearLayout mLL;

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;


    private final int TYPE_NEW_ORDER = 1;//新制单
    private final int TYPE_IN_LIBRARY = 5;//已入库
    private final int TYPE_RETURN_MONEY = 7;//已汇款

    private int type = 1;

    private CommonAdapter<LibraryBean2.ListBean> mCommonAdapter;
    private List<LibraryBean2.ListBean> mDatas = new ArrayList<>();

    @Override
    protected int layoutResId() {
        return R.layout.activity_inlibrary;
    }

    @Override
    protected void init() {
        super.init();


    }

    @Override
    protected void initView() {

        mNewOrder.setSelected(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, 1));

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        long curTime = System.currentTimeMillis();
        long startTime = curTime - 7 * 24 * 60 * 60 * 1000;

        mQueryStart.setText(formatter.format(new Date(startTime)));
        mQueryStop.setText(formatter.format(new Date(curTime)));

    }


    @Override
    protected void initListener() {

//        titleBar.setRightListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mLL.getVisibility() == View.VISIBLE) {
//                    mLL.setVisibility(View.GONE);
//                } else {
//                    mLL.setVisibility(View.VISIBLE);
//                }
//            }
//        });

        refreshLayout.setEnableHeaderTranslationContent(false);
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);


        mCommonAdapter = new CommonAdapter<LibraryBean2.ListBean>(this, R.layout.activity_inlibrary_item, mDatas) {
            @Override
            protected void convert(ViewHolder holder, final LibraryBean2.ListBean libraryBean, int position) {

                TextView mCode = holder.getView(R.id.tv_code);
                TextView mDate = holder.getView(R.id.tv_date);
                TextView mPerson = holder.getView(R.id.tv_person);
                TextView mPrice = holder.getView(R.id.tv_price);

                Button btn_delete = holder.getView(R.id.btn_delete);
                Button btn_edit = holder.getView(R.id.btn_edit);

                mDate.setText(libraryBean.getBuydate());
                mPerson.setText(libraryBean.getApname());

                mCode.setText(libraryBean.getId());
                mPrice.setText(null == libraryBean.getMoney() ? "￥ 0.00" : "￥ " + libraryBean.getMoney());

                if (null == libraryBean.getMoney()) {
                    mPrice.setText("￥ 0.00");
                } else {
                    mPrice.setText("￥" + libraryBean.getMoney());
                }

                switch (type) {
                    case TYPE_NEW_ORDER:
                        btn_delete.setVisibility(View.VISIBLE);
                        btn_edit.setVisibility(View.VISIBLE);
                        break;
                    case TYPE_IN_LIBRARY:
                        btn_delete.setVisibility(View.GONE);
                        btn_edit.setVisibility(View.GONE);
                        break;
                    case TYPE_RETURN_MONEY:
                        btn_delete.setVisibility(View.GONE);
                        btn_edit.setVisibility(View.GONE);
                        break;
                }

                btn_delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(libraryBean);
                    }
                });

                btn_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ListInLibraryActivity.this, InLibraryOrActivity.class);
                        intent.putExtra(Constans.EXTRA_LIBRARY, libraryBean);
                        startActivityForResult(intent, Constans.REQUEST_IN_LIBRARY);
                    }
                });

            }
        };
        mRecyclerView.setAdapter(mCommonAdapter);

        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                switch (type) {
                    case TYPE_NEW_ORDER:

                        break;
                    case TYPE_IN_LIBRARY:
                        Intent intent = new Intent(ListInLibraryActivity.this, InLibraryUpdateActivity.class);
                        intent.putExtra(Constans.EXTRA_INlIBRARY_UPDATE, mDatas.get(position));
                        startActivityForResult(intent,Constans.REQUEST_IN_LIBRARY);
                        break;
                    case TYPE_RETURN_MONEY:
                        Intent intent2 = new Intent(ListInLibraryActivity.this, InLibraryUpdateActivity.class);
                        intent2.putExtra(Constans.EXTRA_INlIBRARY_UPDATE, mDatas.get(position));
                        intent2.putExtra(Constans.EXTRA_INlIBRARY_UPDATE_GONE, "GONE");
                        startActivity(intent2);
                        break;
                }


            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

    }

    /**
     * 显示对话框 提示
     *
     * @param bean
     */
    private void showDialog(final LibraryBean2.ListBean bean) {
        new AlertDialog
                .Builder(this)
                .setMessage("该数据删除后将无法恢复，请确认是否要删除?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(bean);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                .show();
    }

    /**
     * 删除条目
     *
     * @param bean
     */
    private void deleteItem(LibraryBean2.ListBean bean) {
        HttpManager
                .instance()
                .deleteInLibrary(new ReqDeleteInLibraryBean(bean.getId(), bean.getGuid()))
                .compose(new DialogTransformer<Integer>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                               @Override
                               public void onNext(@NonNull Integer num) {
                                   refresh();
                               }
                           }
                );
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage, type);
    }

    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage, type);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataForService2(mCurrentPage, type);
    }

    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    /**
     * 1:新制单5：已入库7：已回款
     *
     * @param pageId
     * @param type
     */
    private void getDataForService(int pageId, int type) {

        HttpManager
                .instance()
                .getInLibraryList(new ReqListInLibraryBean(String.valueOf(pageId), String.valueOf(type)))
                .compose(new DialogTransformer<LibraryBean2>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<LibraryBean2>() {
                               @Override
                               public void onNext(@NonNull LibraryBean2 libraryBean2) {
                                   parseData(libraryBean2);
                               }
                           }
                );
    }

    private void getDataForService2(int pageId, int type) {

        HttpManager
                .instance()
                .getInLibraryList(new ReqListInLibraryBean(String.valueOf(pageId), String.valueOf(type)))
                .subscribe(new ErrorHandleSubscriber<LibraryBean2>() {
                               @Override
                               public void onNext(@NonNull LibraryBean2 libraryBean2) {
                                   parseData(libraryBean2);
                               }
                           }
                );
    }


    private void parseData(@NonNull LibraryBean2 libraryBean2) {

        List<LibraryBean2.ListBean> list = libraryBean2.getList();

        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mDatas.clear();
        }

        if (mCurrentPage > 1 && (list.size() == 0 || list == null)) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }
        mDatas.addAll(list);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("入库单管理");
        titleBar.setRightText("查询");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null) {
            switch (requestCode) {
                case Constans.REQUEST_IN_LIBRARY:

                    String stringExtra = data.getStringExtra(Constans.EXTRA_IN_LIBRARY_TYPE);

                    if (stringExtra.equals("1")) {
                        mInLibrary.setSelected(false);
                        mMonery.setSelected(false);
                        if (mNewOrder.isSelected()) {
                            mNewOrder.setSelected(false);
                        } else {
                            mNewOrder.setSelected(true);
                        }
                        type = TYPE_NEW_ORDER;
                        getDataForService(mCurrentPage, type);
                    } else if (stringExtra.equals("5")) {
                        mNewOrder.setSelected(false);
                        mMonery.setSelected(false);
                        if (mInLibrary.isSelected()) {
                            mInLibrary.setSelected(false);
                        } else {
                            mInLibrary.setSelected(true);
                        }
                        type = TYPE_IN_LIBRARY;
                        getDataForService(mCurrentPage, type);
                    } else if (stringExtra.equals("7")) {
                        mNewOrder.setSelected(false);
                        mInLibrary.setSelected(false);
                        if (mMonery.isSelected()) {
                            mMonery.setSelected(false);
                        } else {
                            mMonery.setSelected(true);
                        }
                        type = TYPE_RETURN_MONEY;
                        getDataForService(mCurrentPage, type);
                    } else {

                    }

                    break;
                default:
                    break;
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.btn_add, R.id.tv_new_order, R.id.tv_in_library, R.id.tv_return_money, R.id.tv_query_start, R.id.tv_query_stop})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.tv_query_start:
                if (pvTime != null) {
                    pvTime.show(v);
                }
                break;
            case R.id.tv_query_stop:
                if (pvTime2 != null) {
                    pvTime2.show(v);
                }
                break;
            case R.id.btn_add:
                //跳采购入库添加界面
                startActivityForResult(new Intent(this, InLibraryOrActivity.class), Constans.REQUEST_IN_LIBRARY);
                break;
            case R.id.tv_new_order://新制单
                mInLibrary.setSelected(false);
                mMonery.setSelected(false);
                if (mNewOrder.isSelected()) {
                    mNewOrder.setSelected(false);
                } else {
                    mNewOrder.setSelected(true);
                }
                type = TYPE_NEW_ORDER;
                getDataForService(mCurrentPage, type);
                break;
            case R.id.tv_in_library://已入库

                mNewOrder.setSelected(false);
                mMonery.setSelected(false);
                if (mInLibrary.isSelected()) {
                    mInLibrary.setSelected(false);
                } else {
                    mInLibrary.setSelected(true);
                }
                type = TYPE_IN_LIBRARY;
                getDataForService(mCurrentPage, type);
                break;
            case R.id.tv_return_money://已回款
                mInLibrary.setSelected(false);
                mNewOrder.setSelected(false);
                if (mMonery.isSelected()) {
                    mMonery.setSelected(false);
                } else {
                    mMonery.setSelected(true);
                }
                type = TYPE_RETURN_MONEY;
                getDataForService(mCurrentPage, type);
                break;

            default:
                break;
        }
    }

}
